<template>
	<view class="nav-page">
		<!-- 顶部导航栏 -->
		<CustomNavbar>
			<view class="navbar-content">
				<view class="nav-left" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<view class="nav-title">导航</view>
				<view class="nav-right">
					<text class="nav-icon">⋯</text>
					<text class="nav-icon-target">◎</text>
				</view>
			</view>
		</CustomNavbar>

		<!-- 地图区域 -->

		<view class="map-wrapper">
			<map class="nav-map" :latitude="mapCenterLatitude" :longitude="mapCenterLongitude" :markers="navMarkers"
				:scale="mapScale" show-location :show-compass="true" :enable-zoom="true" :enable-scroll="true"
				@regionchange="onRegionChange">
			</map>

			<!-- 定位按钮 -->
			<view class="location-btn" @click="refreshLocation">
				<image src="/static/index/定位2@2x.png" class="location-icon" mode="aspectFit"></image>
			</view>
		</view>



		<!-- 底部信息卡片 -->
		<view class="info-card">
			<view class="card-title-row">
				<view class="card-title-wrapper">
					<text class="card-title">{{ stationName }}</text>
				</view>
				<button class="nav-button" @click="startNavigation">导航</button>
			</view>
			<text class="card-address">{{ stationAddress }}</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	import {
		getLocation
	} from '@/utils/location.js'

	// 从存储中获取位置信息
	const getLocationFromStorage = () => {
		return getLocation()
	}

	// 页面参数
	const stationId = ref('')
	const destinationLatitude = ref(34.825817)
	const destinationLongitude = ref(113.55852)
	const stationAddress = ref('')
	const stationName = ref('')
	const currentLatitude = ref(34.825817)
	const currentLongitude = ref(113.55852)

	// 地图中心位置
	const mapCenterLatitude = ref(34.825817)
	const mapCenterLongitude = ref(113.55852)
	const mapScale = ref(15)

	// 导航标记点
	const navMarkers = ref([])

	// 页面加载
	onLoad((options) => {
		// 获取目的地信息
		if (options.stationId) {
			stationId.value = options.stationId
		}
		if (options.latitude) {
			destinationLatitude.value = parseFloat(options.latitude)
		}
		if (options.longitude) {
			destinationLongitude.value = parseFloat(options.longitude)
		}
		if (options.address) {
			stationAddress.value = decodeURIComponent(options.address)
		}
		if (options.name) {
			stationName.value = decodeURIComponent(options.name)
		}

		// 优先从存储中获取当前位置
		const savedLocation = getLocationFromStorage()
		if (savedLocation) {
			currentLatitude.value = savedLocation.latitude
			currentLongitude.value = savedLocation.longitude
		} else {
			// 如果没有存储的位置，尝试获取当前位置
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					currentLatitude.value = res.latitude
					currentLongitude.value = res.longitude
					updateMapCenter()
					updateMarkers()
				},
				fail: () => {
					updateMapCenter()
					updateMarkers()
				}
			})
		}

		updateMapCenter()
		updateMarkers()

		// 监听位置更新事件
		uni.$on('locationUpdated', (locationData) => {
			if (locationData) {
				currentLatitude.value = locationData.latitude
				currentLongitude.value = locationData.longitude
				updateMapCenter()
				updateMarkers()
			}
		})
	})

	// 页面卸载
	onUnload(() => {
		// 移除事件监听
		uni.$off('locationUpdated')
	})

	// 更新地图中心位置（使两个标记点都能显示）
	const updateMapCenter = () => {
		// 计算中心点
		const centerLat = (currentLatitude.value + destinationLatitude.value) / 2
		const centerLng = (currentLongitude.value + destinationLongitude.value) / 2
		mapCenterLatitude.value = centerLat
		mapCenterLongitude.value = centerLng

		// 根据两点距离调整缩放级别
		const latDiff = Math.abs(currentLatitude.value - destinationLatitude.value)
		const lngDiff = Math.abs(currentLongitude.value - destinationLongitude.value)
		const maxDiff = Math.max(latDiff, lngDiff)

		if (maxDiff > 0.1) {
			mapScale.value = 12
		} else if (maxDiff > 0.05) {
			mapScale.value = 13
		} else if (maxDiff > 0.01) {
			mapScale.value = 14
		} else {
			mapScale.value = 15
		}
	}

	// 地图区域变化
	const onRegionChange = (e) => {
		// 可以在这里处理地图区域变化
	}

	// 更新标记点
	const updateMarkers = () => {
		navMarkers.value = [
			// 当前位置标记（蓝色圆圈）
			{
				id: 1,
				latitude: currentLatitude.value,
				longitude: currentLongitude.value,
				iconPath: '/static/index/定位2@2x.png',
				width: 32,
				height: 32,
				anchor: {
					x: 0.5,
					y: 0.5
				},
				title: '我的位置'
			},
			// 目的地标记（红色大头针）
			{
				id: 2,
				latitude: destinationLatitude.value,
				longitude: destinationLongitude.value,
				iconPath: '/static/10090.ico',
				width: 44,
				height: 44,
				anchor: {
					x: 0.5,
					y: 1
				},
				title: stationName.value,
				callout: {
					content: stationAddress.value || stationName.value,
					color: '#333',
					fontSize: 12,
					borderRadius: 6,
					bgColor: '#fff',
					padding: 6,
					display: 'ALWAYS',
					textAlign: 'left',
					borderWidth: 1,
					borderColor: '#e5e5e5'
				}
			}
		]
	}

	// 返回
	const goBack = () => {
		uni.navigateBack()
	}

	// 刷新定位 - 点击后将地图移动到当前位置
	const refreshLocation = () => {
		uni.showLoading({
			title: '定位中...'
		})
		
		// 优先从存储中获取位置
		const savedLocation = getLocationFromStorage()
		if (savedLocation && savedLocation.latitude && savedLocation.longitude) {
			// 使用存储的位置
			currentLatitude.value = savedLocation.latitude
			currentLongitude.value = savedLocation.longitude
			
			// 立即将地图中心移动到当前位置
			moveMapToCurrentLocation()
			
			uni.hideLoading()
			uni.showToast({
				title: '已定位到当前位置',
				icon: 'success',
				duration: 1500
			})
			return
		}
		
		// 如果没有存储的位置，获取实时位置
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				currentLatitude.value = res.latitude
				currentLongitude.value = res.longitude
				
				// 立即将地图中心移动到当前位置
				moveMapToCurrentLocation()
				
				uni.hideLoading()
				uni.showToast({
					title: '定位成功',
					icon: 'success',
					duration: 1500
				})
			},
			fail: (err) => {
				uni.hideLoading()
				console.error('定位失败：', err)
				uni.showToast({
					title: '定位失败，请检查定位权限',
					icon: 'none'
				})
			}
		})
	}
	
	// 将地图移动到当前位置（让当前位置出现在地图窗口中心）
	const moveMapToCurrentLocation = () => {
		if (!currentLatitude.value || !currentLongitude.value) {
			return
		}
		
		// 将地图中心设置为当前位置
		mapCenterLatitude.value = currentLatitude.value
		mapCenterLongitude.value = currentLongitude.value
		
		// 设置合适的缩放级别，确保当前位置清晰可见
		mapScale.value = 16
		
		// 更新标记点
		updateMarkers()
		
		console.log('地图已移动到当前位置：', {
			latitude: currentLatitude.value,
			longitude: currentLongitude.value,
			scale: mapScale.value
		})
	}

	// 开始导航
	const startNavigation = () => {
		// 使用 uni.openLocation 打开地图应用进行导航
		uni.openLocation({
			latitude: destinationLatitude.value,
			longitude: destinationLongitude.value,
			name: stationName.value,
			address: stationAddress.value,
			success: () => {
				console.log('打开地图成功')
			},
			fail: (err) => {
				console.error('打开地图失败：', err)
				uni.showToast({
					title: '打开地图失败',
					icon: 'none'
				})
			}
		})
	}
</script>

<style scoped>
	.nav-page {
		width: 100%;
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}

	/* 导航栏样式 */
	::v-deep .custom-navbar {
		background: linear-gradient(135deg, #2575fc, #6a11cb) !important;
	}

	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		position: relative;
	}

	.nav-left {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60rpx;
		height: 88rpx;
	}

	.back-icon {
		color: #fff;
		font-size: 56rpx;
		font-weight: 300;
		line-height: 88rpx;
		transform: scaleY(1.3);
	}

	.nav-title {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		line-height: 88rpx;
	}

	.nav-right {
		display: flex;
		align-items: center;
		gap: 30rpx;
	}

	.nav-icon {
		color: #fff;
		font-size: 36rpx;
	}

	.nav-icon-target {
		color: #fff;
		font-size: 32rpx;
	}

	/* 地图区域 */
	.map-wrapper {
		top: -300rpx;
		width: 720rpx;
		height: 1200rpx;
		flex: 1;
		position: relative;
		background-color: #fff;
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.nav-map {
		width: 100%;
		height: 100%;
	}

	/* 定位按钮 */
	.location-btn {
		position: absolute;
		right: 30rpx;
		bottom: 30rpx;
		width: 80rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		z-index: 10;
	}

	.location-icon {
		width: 40rpx;
		height: 40rpx;
	}

	/* 底部信息卡片 */
	.info-card {
		background-color: #fff;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.03);
	}

	.card-title-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 15rpx;
		gap: 20rpx;
	}

	.card-title-wrapper {
		flex: 1;
		min-width: 0;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
		line-height: 1.4;
		word-break: break-all;
	}

	.nav-button {
		background-color: #2575fc;
		color: #fff;
		padding: 15rpx 40rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: 500;
		border: none;
		white-space: nowrap;
		box-shadow: 0 2rpx 8rpx rgba(37, 117, 252, 0.3);
		transition: all 0.3s ease;
	}

	.nav-button:active {
		transform: scale(0.98);
		box-shadow: 0 1rpx 4rpx rgba(37, 117, 252, 0.3);
	}

	.card-address {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
		display: block;
	}
</style>